package com.example.mapinformationandroid.UI;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.util.ArrayMap;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.example.mapinformationandroid.ConstantData.Define;
import com.example.mapinformationandroid.Http.HTTPBase;
import com.example.mapinformationandroid.Http.OBSBASE;
import com.example.mapinformationandroid.Model.Information;
import com.example.mapinformationandroid.Model.ResponseBase;
import com.example.mapinformationandroid.R;
import com.example.mapinformationandroid.Util.GlideImageEngine;
import com.example.mapinformationandroid.Util.LocationUtils;
import com.obs.services.ObsClient;
import com.obs.services.exception.ObsException;
import com.obs.services.model.HeaderResponse;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

public class AddInformation extends AppCompatActivity implements View.OnClickListener {
    protected EditText information_content, information_title, information_place;
    protected ImageView imageView1, imageView2, imageView3, imageView4;
    protected Button btn_addInformation;
    protected String token;
    protected String cox, coy, place;
    protected int postcodes = 0;
    private static final int REQUEST_CODE_CHOOSE = 0x13;
    private Information information;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_information);
        initView();
        initData();
    }

    private void initView() {
        btn_addInformation = findViewById(R.id.btn_add_information);
        btn_addInformation.setOnClickListener(this);
        information_content = findViewById(R.id.et_add_content);
        information_title = findViewById(R.id.et_add_title);
        information_place = findViewById(R.id.et_add_place);
        imageView1 = findViewById(R.id.img_add_information1);
        imageView1.setOnClickListener(this);
        imageView2 = findViewById(R.id.img_add_information2);
        imageView3 = findViewById(R.id.img_add_information3);
        imageView4 = findViewById(R.id.img_add_information4);
        imageView2.setOnClickListener(this);
        imageView3.setOnClickListener(this);
        imageView4.setOnClickListener(this);
    }

    private void initData() {
        getLocationData();
        information = new Information();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_add_information:

                information = getInformationData(information);
                if (rectifyInformation(information)) {
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            OBSPicture(information);
                        }
                    }).start();
                    getRequest(informationToMap(information));
                }
                break;
            case R.id.img_add_information1:
                initPermission();

            case R.id.img_add_information2:

            case R.id.img_add_information3:

            case R.id.img_add_information4:


        }
    }

    private boolean rectifyInformation(Information information) {
        if (information.getTitle().isEmpty() || information.getContent().isEmpty()) {
            Toast.makeText(AddInformation.this, "请填写完数据", Toast.LENGTH_SHORT).show();
            return false;
        } else {
            return true;
        }
    }

    //吧资讯数据转化为Map
    private Map<String, String> informationToMap(Information information) {
        Map<String, String> map_information = new ArrayMap<>();
        map_information.put(Define.InformationDefine.TITLE, information.getTitle());
        map_information.put(Define.InformationDefine.CONTENT, information.getContent());
        map_information.put(Define.InformationDefine.PICTURE, information.getPicture());
        map_information.put(Define.InformationDefine.CRETE_USER_ID, String.valueOf(information.getCreate_user_id()));
        map_information.put(Define.InformationDefine.POST_CODES, String.valueOf(information.getPostcodes()));
        map_information.put(Define.InformationDefine.PLACE, information.getPlace());
        map_information.put(Define.InformationDefine.COORDINATE_X, information.getCoordinate_x());
        map_information.put(Define.InformationDefine.COORDINATE_Y, information.getCoordinate_y());
        if (!token.isEmpty()) {
            map_information.put(Define.UserDefine.USER_TOKEN, token);
        }
        return map_information;
    }

    //获取定位数据与资讯数据
    private void getLocationData() {
        LocationUtils locationUtils = new LocationUtils(this, new AMapLocationListener() {
            @Override
            public void onLocationChanged(AMapLocation aMapLocation) {
                if (aMapLocation.getErrorCode() == 0) {
                    cox = String.valueOf(aMapLocation.getLatitude());
                    coy = String.valueOf(aMapLocation.getLongitude());
                    postcodes = Integer.parseInt(aMapLocation.getAdCode());
                    place = aMapLocation.getAddress();
                    aMapLocation.getAddress();


                } else {

                    Toast.makeText(AddInformation.this, "定位失败", Toast.LENGTH_SHORT).show();
                }
            }
        });

        locationUtils.startLocation();
    }

    //获取编辑内容
    private Information getInformationData(Information information) {
        information.setContent(information_content.getText().toString());
        information.setTitle(information_title.getText().toString());
        information.setCoordinate_x(cox);
        information.setCoordinate_y(coy);
        information.setPicture(Define.HuaWeiObsDefine.OBS_PICTURE_PATH_HEAD+information.getBitmap_path());
        information.setPostcodes(postcodes);
        if (information_place.getText().toString().isEmpty()) {
            information.setPlace(place);
        } else {
            information.setPlace(information_place.getText().toString());
        }
        SharedPreferences sharedPreferences = getSharedPreferences("user", Activity.MODE_PRIVATE);
        int user_id = sharedPreferences.getInt(Define.UserDefine.USER_ID, 0);
        if (user_id != 0) {
            information.setCreate_user_id(user_id);
        }
        token = sharedPreferences.getString(Define.UserDefine.USER_TOKEN, "");
        return information;
    }


    private void getRequest(Map<String, String> map) {
        final HTTPBase httpBase = new HTTPBase();
        httpBase.create_information(map, new Observer<ResponseBase>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(ResponseBase value) {
                if (value.getCode() == Define.HttpDefine.TOKEN_INVALID) {
                    startActivity(new Intent(AddInformation.this, Login.class));
                    SharedPreferences sharedPreferences = getSharedPreferences("user", Activity.MODE_PRIVATE);
                    sharedPreferences.edit().clear().apply();
                    finish();
                } else {
                    if (value.getCode() == Define.HttpDefine.HTTP_SUCCESS) {
                        Toast.makeText(AddInformation.this, "发布成功", Toast.LENGTH_SHORT).show();
                    } else {

                        Toast.makeText(AddInformation.this, "发布失败", Toast.LENGTH_SHORT).show();
                    }
                }
            }

            @Override
            public void onError(Throwable e) {
                Toast.makeText(AddInformation.this, "请检查网络", Toast.LENGTH_SHORT).show();
                Log.d("add_information", e.toString());
            }

            @Override
            public void onComplete() {

            }
        });
    }

    //上传华为云OBS图片
    private void OBSPicture(Information information) {
        OBSBASE obsbase  = new OBSBASE();
        obsbase.commitPicture(information);
        obsbase.OBSClose();

    }

    //请求权限
    private void initPermission() {


        if (ContextCompat.checkSelfPermission(AddInformation.this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED ||ContextCompat.checkSelfPermission(AddInformation.this, Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED||ContextCompat.checkSelfPermission(AddInformation.this, Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED||ContextCompat.checkSelfPermission(AddInformation.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {//未开启定位权限
            //开启定位权限,200是标识码
            ActivityCompat.requestPermissions(AddInformation.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.CAMERA,Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE}, 200);
        }else{
            ChooserImg();
        }

    }

    //从相册读取图片
    private void ChooserImg() {
        Matisse.from(AddInformation.this)
                .choose(MimeType.ofAll(), false)
                .capture(true)
                .captureStrategy(new CaptureStrategy(true,"com.example.mapinformationandroid.fileprovider"))
                .countable(true)
                .maxSelectable(1) // 图片选择的最多数量
                .gridExpectedSize(getResources().getDimensionPixelSize(R.dimen.grid_expected_size))
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                .thumbnailScale(0.85f) // 缩略图的比例
                .imageEngine(new GlideImageEngine()) // 使用的图片加载引擎
                .forResult(REQUEST_CODE_CHOOSE); // 设置作为标记的请求码
    }

    @SuppressLint("CheckResult")
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        RequestOptions options = new RequestOptions();
        options.centerCrop();
        if (resultCode == RESULT_OK) {// 操作成功了
            switch (requestCode) {
                case REQUEST_CODE_CHOOSE:// 图库选择图片
                    List<String> img_path = Matisse.obtainPathResult(data);
                    List<String> imgliststr = new ArrayList<>();
                    for (String path : img_path) {
                        imgliststr.add(path);
                        Glide.with(this)
                                .load(path)
                                .apply(options)
                                .into(imageView1);
                        information.setBitmap_path(path);
                        information.setBitmap_local_path(path);
                    }
                    Log.d("AddInformation", "onActivityResult拿到了" + imgliststr.size() + "张图片:" + imgliststr);
                    break;
            }
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(requestCode == 200){
            ChooserImg();
        }
    }
}
